﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Threading;
using System.IO.IsolatedStorage;
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;
using DataBasetestApp.ServiceReference2;

namespace DataBasetestApp
{
    public partial class MatchUpdatePage : PhoneApplicationPage
    {
        // set up isolated storage
        IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

        public MatchUpdatePage()
        {
            InitializeComponent();
            InitializeSettings();
        }

        // Set up vaiables
        public string HomeTeam, AwayTeam, Location, Competition, Time;
        public int id, mins, user_id;

        public string dateTime = DateTime.Now.ToString();
        public string Live = "Y";
        public string Score = "0-0 - 0-0";
        public int Minute = 0;
        public int minuteStarted;
        bool buttonClicked;
        bool secondHalfStarted;
        bool halfTimeReached;

        bool matchOver = false; 

        // Method to update the match on the database
        void UpdateMatch()
        {
            try
            {
                Score = goalsBox1.Text.ToString() + "-" + pointsBox1.Text.ToString() + " - " + goalsBox2.Text.ToString() + "-" + pointsBox2.Text.ToString();
                GAALiveServiceClient client = new GAALiveServiceClient();
                client.UpdateMatchCompleted +=
                    new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(client_UpdateMatchCompleted);
                client.UpdateMatchAsync(id, Score, Minute.ToString(), user_id);
            }
            catch (Exception e)
            {
                MessageBoxResult n = MessageBox.Show(e.Message);
            }
        }

        // Run this when the page is loaded
        // Extract the settings from isolated storage and reload to certain parts of the page
        private void InitializeSettings()
        {
            if (settings.Contains("matchStartedButNotFinished"))
            {
                if ((bool)settings["matchStartedButNotFinished"] == true)
                {
                    // Parse the match information
                    button2.Content = "Throw-In";

                    if (settings.Contains("team1Goals"))
                    {
                        goalsBox1.Text = (string)settings["team1Goals"];
                    }
                    if (settings.Contains("team1points"))
                    {
                        pointsBox1.Text = (string)settings["team1points"];
                    }
                    if (settings.Contains("team2Goals"))
                    {
                        goalsBox2.Text = (string)settings["team2Goals"];
                    }
                    if (settings.Contains("team2Points"))
                    {
                        pointsBox2.Text = (string)settings["team2Points"];
                    }
                    if (settings.Contains("homeTeam"))
                    {
                        teamBlock1.Text = (string)settings["homeTeam"];
                        HomeTeam = (string)settings["homeTeam"];
                    }
                    if (settings.Contains("awayTeam"))
                    {
                        teamBlock2.Text = (string)settings["awayTeam"];
                        AwayTeam = (string)settings["awayTeam"];
                    }
                    if (settings.Contains("ID"))
                    {
                        id = (int)settings["ID"];
                    }
                    if (settings.Contains("minuteStarted"))
                    {
                        minuteStarted = (int)settings["minuteStarted"];
                    }
                    if (settings.Contains("mins"))
                    {
                        mins = (int)settings["mins"];
                    }
                    if (settings.Contains("time"))
                    {
                        Time = (string)settings["time"];
                    }
                    if (settings.Contains("userID"))
                    {
                        string temp = (string)settings["userID"];
                        user_id = Convert.ToInt32(temp);
                    }
                    if (settings.Contains("Location"))
                    {
                        Location = (string)settings["Location"];
                    }
                    if (settings.Contains("Competition"))
                    {
                        Competition = (string)settings["Competition"];
                    }

                    buttonClicked = true;
                    //button2.Content = "Update Score";
                    if (settings.Contains("matchOver"))
                    {
                        matchOver = (bool)settings["matchOver"];
                    }
                    if (settings.Contains("halfTimeReached"))
                    {
                        if ((bool)settings["halfTimeReached"] == true)
                        {
                            halfTimeReached = true;
                            timeBlock.Text = "HT";

                            if (settings.Contains("secondHalfStarted"))
                            {
                                if (!(bool)settings["secondHalfStarted"])
                                {
                                    timeBlock.Text = "HT";
                                }
                                else
                                {
                                    timeBlock.Text = "";
                                    secondHalfStarted = true;
                                }
                            }
                        }
                    }
                }
            }
        }

        // If you are navigating to the page after leaving it mid-match, will jump back to here
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            InitializeSettings();

            if (NavigationContext.QueryString.TryGetValue("HomeTeam", out HomeTeam))
            {
                teamBlock1.Text = HomeTeam;
            }
            if (NavigationContext.QueryString.TryGetValue("AwayTeam", out AwayTeam))
            {
                teamBlock2.Text = AwayTeam;
            }
            NavigationContext.QueryString.TryGetValue("Location", out Location);
            NavigationContext.QueryString.TryGetValue("Competition", out Competition);          
        }

        // Callback from creating a match
        void client_CreateMatchCompleted(object sender, CreateMatchCompletedEventArgs c)
        {
            id = c.Result;
            string date = DateTime.Now.ToString();
            settings["matchOver"] = false;
            settings["matchStartedButNotFinished"] = true; //---------------> When is id set??? We need this to create the container.
            //settings["secondHalfStarted"] = false;
            settings["halfTimeReached"] = false;

            // get the user ID for this user
            string user_idString = (string)settings["Username"];
            GAALiveServiceClient client = new GAALiveServiceClient();
            client.GetuserIDCompleted +=
                        new EventHandler<GetuserIDCompletedEventArgs>(client_GetuserIDCompleted);
            client.GetuserIDAsync(user_idString);
        }

        // Add a Goal to team 1
        private void Goals_Click(object sender, RoutedEventArgs e)
        {
            // if the match is over then advise them of this
            if (matchOver)
            {
                MessageBoxResult n = MessageBox.Show("This match has finished, Pease begin a new one if you wish to report on a new match.", "Match finished!", MessageBoxButton.OK);

                if (n == MessageBoxResult.OK)
                {
                    NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                    //NavigationService.GoBack()
                }
            }
            else
            {
                // Verify that it is not half time at the moment
                if (buttonClicked)
                {
                    if (Time == null)
                    {
                        Time = "30";
                    }
                    if (timeBlock.Text == "HT")
                    {
                        MessageBox.Show("The 2nd half has not begun yet." + Environment.NewLine + "Please click 'Throw-In' to begin 2nd half");
                    }

                    else
                    {
                        // if the second half has started then calculate the time differently
                        if (secondHalfStarted)
                        {
                            int mins = Int32.Parse(Time);
                            Minute = (mins + (DateTime.Now.Minute - minuteStarted + 1));
                            if (Minute < 0)
                            {
                                Minute += 60;
                            }
                            timeBlock.Text = Minute.ToString();
                            int goals = Int32.Parse(goalsBox1.Text);
                            goals++;
                            goalsBox1.Text = goals.ToString();
                            settings["team1Goals"] = goalsBox1.Text;

                            //AddGoals();
                            UpdateMatch();
                        }
                        else
                        {
                            Minute = (DateTime.Now.Minute - minuteStarted + 1);

                            if (Minute < 0)
                            {
                                Minute += 60;
                            }

                            timeBlock.Text = Minute.ToString();
                            int goals = Int32.Parse(goalsBox1.Text);
                            goals++;
                            goalsBox1.Text = goals.ToString();
                            settings["team1Goals"] = goalsBox1.Text;
                            settings["halfTimeReached"] = false;
                            //settings["secondHalfStarted"] = false;

                            //AddGoals();
                            UpdateMatch();
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Match has not yet started. Click 'Start Match' to begin.");
                }
            }
        }

        // Subtract a goal from team 1 -- Here in case you add a point by mistake, or if the referee changes his mind (which never happens!!!!)
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            int goals = Int32.Parse(goalsBox1.Text);
            if (matchOver)
            {
                MessageBoxResult n = MessageBox.Show("This match has finished, Pease begin a new one if you wish to report on a new match.", "Match finished!", MessageBoxButton.OK);

                if (n == MessageBoxResult.OK)
                {
                    NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                    //NavigationService.GoBack()
                }
            }
            else
            {
                // Verify that it is not half time at the moment
                if (buttonClicked)
                {
                    if (Time == null)
                    {
                        Time = "30";
                    }
                    if (goals > 0)
                    {
                        if (timeBlock.Text == "HT")
                        {
                            MessageBox.Show("The 2nd half has not begun yet." + Environment.NewLine + "Please click 'Throw-In' to begin 2nd half");
                        }

                        else
                        {
                            if (secondHalfStarted)
                            {
                                int mins = Int32.Parse(Time);
                                Minute = (mins + (DateTime.Now.Minute - minuteStarted + 1));
                                if (Minute < 0)
                                {
                                    Minute += 60;
                                }
                                timeBlock.Text = Minute.ToString();
                                goals--;
                                goalsBox1.Text = goals.ToString();
                                settings["team1Goals"] = goalsBox1.Text;

                                UpdateMatch();
                            }
                            else
                            {
                                Minute = (DateTime.Now.Minute - minuteStarted + 1);
                                if (Minute < 0)
                                {
                                    Minute += 60;
                                }
                                timeBlock.Text = Minute.ToString();
                                goals--;
                                goalsBox1.Text = goals.ToString();
                                settings["team1Goals"] = goalsBox1.Text;
                                settings["halfTimeReached"] = false;
                                //settings["secondHalfStarted"] = false;

                                UpdateMatch();
                            }
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Match has not yet started. Click 'Start Match' to begin.");
                }
            }
        }

        // add a point to team 1
        private void pointsAdd1_Click(object sender, RoutedEventArgs e)
        {
            if (matchOver)
            {
                MessageBoxResult n = MessageBox.Show("This match has finished, Pease begin a new one if you wish to report on a new match.", "Match finished!", MessageBoxButton.OK);

                if (n == MessageBoxResult.OK)
                {
                    NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                    //NavigationService.GoBack()
                }
            }
            else
            {
                if (buttonClicked)
                {
                    if (Time == null)
                    {
                        Time = "30";
                    }
                    if (timeBlock.Text == "HT")
                    {
                        MessageBox.Show("The 2nd half has not begun yet." + Environment.NewLine + "Please click 'Throw-In' to begin 2nd half");
                    }

                    else
                    {
                        // Verify that it is not half time at the moment
                        if (secondHalfStarted)
                        {
                            // if the second half has started then calculate the time differently
                            // Update the score of the already created match
                            mins = Int32.Parse(Time);
                            // time keeping
                            Minute = (mins + (DateTime.Now.Minute - minuteStarted + 1));
                            if (Minute < 0)
                            {
                                Minute += 60;
                            }
                            timeBlock.Text = Minute.ToString();
                            int points = Int32.Parse(pointsBox1.Text);
                            points++;
                            pointsBox1.Text = points.ToString();
                            settings["team1points"] = pointsBox1.Text;

                            //AddPoints();
                            UpdateMatch();
                        }
                        else
                        {
                            Minute = (DateTime.Now.Minute - minuteStarted + 1);
                            if (Minute < 0)
                            {
                                Minute += 60;
                            }
                            timeBlock.Text = Minute.ToString();
                            int points = Int32.Parse(pointsBox1.Text);
                            points++;
                            pointsBox1.Text = points.ToString();
                            settings["team1points"] = pointsBox1.Text;
                            settings["halfTimeReached"] = false;
                            //settings["secondHalfStarted"] = null;

                            //AddPoints();
                            UpdateMatch();
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Match has not yet started. Click 'Start Match' to begin.");
                }
            }
        }

        // Subtract a point from team 1 -- In case of mistakes
        private void pointsMinus1_Click(object sender, RoutedEventArgs e)
        {
            int points = Int32.Parse(pointsBox1.Text);
            if (matchOver)
            {
                MessageBoxResult n = MessageBox.Show("This match has finished, Pease begin a new one if you wish to report on a new match.", "Match finished!", MessageBoxButton.OK);

                if (n == MessageBoxResult.OK)
                {
                    NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                    //NavigationService.GoBack()
                }
            }
            else
            {
                // Verify that it is not half time at the moment
                if (buttonClicked)
                {
                    if (Time == null)
                    {
                        Time = "30";
                    }
                    if (points > 0)
                    {
                        if (timeBlock.Text == "HT")
                        {
                            MessageBox.Show("The 2nd half has not begun yet." + Environment.NewLine + "Please click 'Throw-In' to begin 2nd half");
                        }

                        else
                        {
                            if (secondHalfStarted)
                            {
                                // Update the score of the already created match
                                int mins = Int32.Parse(Time);
                                Minute = (mins + (DateTime.Now.Minute - minuteStarted + 1));
                                if (Minute < 0)
                                {
                                    Minute += 60;
                                }
                                timeBlock.Text = Minute.ToString();
                                timeBlock.Text = Minute.ToString();
                                points--;
                                pointsBox1.Text = points.ToString();
                                settings["team1points"] = pointsBox1.Text;

                                UpdateMatch();
                            }
                            else
                            {
                                Minute = (DateTime.Now.Minute - minuteStarted + 1);
                                if (Minute < 0)
                                {
                                    Minute += 60;
                                }
                                timeBlock.Text = Minute.ToString();
                                points--;
                                pointsBox1.Text = points.ToString();
                                settings["team1points"] = pointsBox1.Text;
                                settings["halfTimeReached"] = false;
                                settings["secondHalfStarted"] = null;

                                UpdateMatch();
                            }
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Match has not yet started. Click 'Start Match' to begin.");
                }
            }
        }

        // add a goal to the score for team 1
        private void goalsAdd2_Click(object sender, RoutedEventArgs e)
        {
            if (matchOver)
            {
                MessageBoxResult n = MessageBox.Show("This match has finished, Pease begin a new one if you wish to report on a new match.", "Match finished!", MessageBoxButton.OK);

                if (n == MessageBoxResult.OK)
                {
                    NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                    //NavigationService.GoBack()
                }
            }
            else
            {
                if (buttonClicked)
                {
                    if (Time == null)
                    {
                        Time = "30";
                    }
                    if (timeBlock.Text == "HT")
                    {
                        MessageBox.Show("The 2nd half has not begun yet." + Environment.NewLine + "Please click 'Throw-In' to begin 2nd half");
                    }

                    else
                    {
                        if (secondHalfStarted)
                        {
                            // Update the score of the already created match
                            int mins = Int32.Parse(Time);
                            Minute = (mins + (DateTime.Now.Minute - minuteStarted + 1));
                            if (Minute < 0)
                            {
                                Minute += 60;
                            }
                            timeBlock.Text = Minute.ToString();
                            int goals = Int32.Parse(goalsBox2.Text);
                            goals++;
                            goalsBox2.Text = goals.ToString();
                            settings["team2Goals"] = goalsBox2.Text;

                            UpdateMatch();
                        }
                        else
                        {

                            Minute = (DateTime.Now.Minute - minuteStarted + 1);
                            if (Minute < 0)
                            {
                                Minute += 60;
                            }
                            timeBlock.Text = Minute.ToString();
                            int goals = Int32.Parse(goalsBox2.Text);
                            goals++;
                            goalsBox2.Text = goals.ToString();
                            settings["team2Goals"] = goalsBox2.Text;
                            settings["halfTimeReached"] = false;
                            //settings["secondHalfStarted"] = null;

                            UpdateMatch();
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Match has not yet started. Click 'Start Match' to begin.");
                }
            }
        }

        // Subtract a goal from team 2
        private void goalsMinus2_Click(object sender, RoutedEventArgs e)
        {
            int goals = Int32.Parse(goalsBox2.Text);
            if (matchOver)
            {
                MessageBoxResult n = MessageBox.Show("This match has finished, Pease begin a new one if you wish to report on a new match.", "Match finished!", MessageBoxButton.OK);

                if (n == MessageBoxResult.OK)
                {
                    NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                    //NavigationService.GoBack()
                }
            }
            else
            {
                if (buttonClicked)
                {
                    if (Time == null)
                    {
                        Time = "30";
                    }
                    if (goals > 0)
                    {
                        if (timeBlock.Text == "HT")
                        {
                            MessageBox.Show("The 2nd half has not begun yet." + Environment.NewLine + "Please click 'Throw-In' to begin 2nd half");
                        }

                        else
                        {
                            if (secondHalfStarted)
                            {
                                // Update the score of the already created match
                                int mins = Int32.Parse(Time);
                                Minute = (mins + (DateTime.Now.Minute - minuteStarted + 1));
                                if (Minute < 0)
                                {
                                    Minute += 60;
                                }
                                timeBlock.Text = Minute.ToString();
                                goals--;
                                goalsBox2.Text = goals.ToString();
                                settings["team2Goals"] = goalsBox2.Text;

                                UpdateMatch();
                            }
                            else
                            {
                                Minute = (DateTime.Now.Minute - minuteStarted + 1);
                                if (Minute < 0)
                                {
                                    Minute += 60;
                                }
                                timeBlock.Text = Minute.ToString();
                                goals--;
                                goalsBox2.Text = goals.ToString();
                                settings["team2Goals"] = goalsBox2.Text;
                                settings["halfTimeReached"] = false;
                                //settings["secondHalfStarted"] = null;

                                UpdateMatch();
                            }
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Match has not yet started. Click 'Start Match' to begin.");
                }
            }
        }

        // add a point to team 2
        private void pointsAdd2_Click_1(object sender, RoutedEventArgs e)
        {
            if (matchOver)
            {
                MessageBoxResult n = MessageBox.Show("This match has finished, Pease begin a new one if you wish to report on a new match.", "Match finished!", MessageBoxButton.OK);

                if (n == MessageBoxResult.OK)
                {
                    NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                    //NavigationService.GoBack()
                }
            }
            else
            {
                if (buttonClicked)
                {
                    if (Time == null)
                    {
                        Time = "30";
                    }
                    if (timeBlock.Text == "HT")
                    {
                        MessageBox.Show("The 2nd half has not begun yet." + Environment.NewLine + "Please click 'Throw-In' to begin 2nd half");
                    }

                    else
                    {
                        if (secondHalfStarted)
                        {
                            // Update the score of the already created match
                            mins = Int32.Parse(Time);
                            Minute = (mins + (DateTime.Now.Minute - minuteStarted + 1));
                            if (Minute < 0)
                            {
                                Minute += 60;
                            }
                            timeBlock.Text = Minute.ToString();
                            int points = Int32.Parse(pointsBox2.Text);
                            points++;
                            pointsBox2.Text = points.ToString();
                            settings["team2Points"] = pointsBox2.Text;

                            UpdateMatch();
                        }
                        else
                        {
                            Minute = (DateTime.Now.Minute - minuteStarted + 1);
                            if (Minute < 0)
                            {
                                Minute += 60;
                            }
                            timeBlock.Text = Minute.ToString();
                            int points = Int32.Parse(pointsBox2.Text);
                            points++;
                            pointsBox2.Text = points.ToString();
                            settings["team2Points"] = pointsBox2.Text;
                            settings["halfTimeReached"] = false;
                            //settings["secondHalfStarted"] = null;

                            UpdateMatch();
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Match has not yet started. Click 'Start Match' to begin.");
                }
            }
        }

        // subtract a point from team 2
        private void pointsMinus2_Click_1(object sender, RoutedEventArgs e)
        {
            int points = Int32.Parse(pointsBox2.Text);
            if (matchOver)
            {
                MessageBoxResult n = MessageBox.Show("This match has finished, Pease begin a new one if you wish to report on a new match.", "Match finished!", MessageBoxButton.OK);

                if (n == MessageBoxResult.OK)
                {
                    NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                    //NavigationService.GoBack()
                }
            }
            else
            {
                if (buttonClicked)
                {
                    if (points > 0)
                    {
                        if (Time == null)
                        {
                            Time = "30";
                        }
                        if (timeBlock.Text == "HT")
                        {
                            MessageBox.Show("The 2nd half has not begun yet." + Environment.NewLine + "Please click 'Throw-In' to begin 2nd half");
                        }

                        else
                        {
                            if (secondHalfStarted)
                            {
                                // Update the score of the already created match
                                int mins = Int32.Parse(Time);
                                Minute = (mins + (DateTime.Now.Minute - minuteStarted + 1));
                                if (Minute < 0)
                                {
                                    Minute += 60;
                                }
                                timeBlock.Text = Minute.ToString();
                                points--;
                                pointsBox2.Text = points.ToString();
                                settings["team2Points"] = pointsBox2.Text;

                                UpdateMatch();
                            }
                            else
                            {
                                Minute = (DateTime.Now.Minute - minuteStarted + 1);
                                if (Minute < 0)
                                {
                                    Minute += 60;
                                }
                                timeBlock.Text = Minute.ToString();
                                points--;
                                pointsBox2.Text = points.ToString();
                                settings["team2Points"] = pointsBox2.Text;
                                settings["halfTimeReached"] = false;
                                secondHalfStarted = false;
                                //settings["secondHalfStarted"] = null;

                                UpdateMatch();
                            }
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Match has not yet started. Click 'Start Match' to begin.");
                }
            }
        }

        // Live scores Button
        private void button1_Click_1(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

        // Start match / Throw-In button
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            if (matchOver)
            {
                MessageBoxResult n = MessageBox.Show("This match has finished, Pease begin a new one if you wish to report on a new match.", "Match finished!", MessageBoxButton.OK);

                if (n == MessageBoxResult.OK)
                {
                    NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                    //NavigationService.GoBack()
                }
            }

            else
            {
                if (!buttonClicked)
                {
                    // Create a new match and store it in the database
                    GAALiveServiceClient client = new GAALiveServiceClient();
                    client.CreateMatchCompleted +=
                        new EventHandler<CreateMatchCompletedEventArgs>(client_CreateMatchCompleted);
                    client.CreateMatchAsync(dateTime, Location, Live, Score, HomeTeam, AwayTeam, Competition, Minute.ToString());
                    button2.Content = "Throw-In";
                    buttonClicked = true;
                    settings["buttonClicked"] = true;
                    minuteStarted = DateTime.Now.Minute;
                    timeBlock.Text = Minute.ToString();
                }
                else
                {
                    if (halfTimeReached)
                    {
                        if (Time == null)
                        {
                            Time = "30";
                        }
                        // Update the score of the already created match
                        mins = Int32.Parse(Time);
                        minuteStarted = DateTime.Now.Minute;
                        Minute = (mins + (DateTime.Now.Minute - minuteStarted + 1));
                        timeBlock.Text = Minute.ToString();
                        Score = goalsBox1.Text.ToString() + "-" + pointsBox1.Text.ToString() + " - " + goalsBox2.Text.ToString() + "-" + pointsBox2.Text.ToString();
                        GAALiveServiceClient client = new GAALiveServiceClient();
                        client.UpdateMatchCompleted +=
                            new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(client_UpdateMatchCompleted);
                        client.UpdateMatchAsync(id, Score, Minute.ToString(), user_id);
                        timeBlock.Text = Minute.ToString();
                        secondHalfStarted = true;
                        settings["secondHalfStarted"] = true;
                    }
                }
            }
        }

        // Callback from the match update Asynch method
        void client_UpdateMatchCompleted(object sender, EventArgs c)
        {
            // First part here is in case the screen has been navigated to from another page mid-match
            // variables need to be set up again
            if (settings.Contains("homeTeam"))
            {
                HomeTeam = (string)settings["homeTeam"];
            }
            if (settings.Contains("awayTeam"))
            {
                AwayTeam = (string)settings["awayTeam"];
            }
            if (settings.Contains("time"))
            {
                Time = (string)settings["time"];
            }
            if (settings.Contains("Location"))
            {
                Location = (string)settings["Location"];
            }
            if (settings.Contains("Competition"))
            {
                Competition = (string)settings["Competition"];
            }

            // Set these settings in Isolated storage
            settings["team1Goals"] = goalsBox1.Text.ToString();
            settings["team1points"] = pointsBox1.Text.ToString();
            settings["team2Goals"] = goalsBox2.Text.ToString();
            settings["team2Points"] = pointsBox2.Text.ToString();
            settings["homeTeam"] = teamBlock1.Text.ToString();
            settings["awayTeam"] = teamBlock2.Text.ToString();
            settings["ID"] = id;
            settings["minuteStarted"] = minuteStarted;
            settings["mins"] = mins;
            settings["time"] = Time;
            settings["userID"] = user_id.ToString();
            settings["Location"] = Location;
            settings["Competition"] = Competition;
        }

        void client_FinishMatchCompleted(object sender, EventArgs c)
        {
            timeBlock.Text = "FT";
            // Delete the settings from isolated storage
            settings.Remove("matchStartedButNotFinished");
            settings.Remove("matchOver");
            settings.Remove("team1Goals");
            settings.Remove("team1points");
            settings.Remove("team2Goals");
            settings.Remove("team2Points");
            settings.Remove("homeTeam");
            settings.Remove("awayTeam");
            settings.Remove("ID");
            settings.Remove("minuteStarted");
            settings.Remove("mins");
            settings.Remove("time");
            matchOver = true;
        }

        // Callback from the get user id Asynch method
        // Sets the result to the user_id variable in the code so it can be used to update matches
        void client_GetuserIDCompleted(object sender, GetuserIDCompletedEventArgs c)
        {
            user_id = c.Result;
        }

        // HT Button
        private void HTButton_Click(object sender, RoutedEventArgs e)
        {
            string temp = "HT";
            timeBlock.Text = Minute.ToString();
            Score = goalsBox1.Text.ToString() + "-" + pointsBox1.Text.ToString() + " - " + goalsBox2.Text.ToString() + "-" + pointsBox2.Text.ToString();
            GAALiveServiceClient client = new GAALiveServiceClient();
            client.UpdateMatchCompleted +=
                new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(client_UpdateMatchCompleted);
            client.UpdateMatchAsync(id, Score, temp, user_id);
            halfTimeReached = true;
            settings["halfTimeReached"] = true;
            button2.Content = "Throw-In";
            timeBlock.Text = temp;
            settings["minute"] = Minute;
            settings["time"] = "30";
        }

        // FT Button
        private void FTButton_Click(object sender, RoutedEventArgs e)
        {
            if (secondHalfStarted)
            {
                MessageBoxResult n = MessageBox.Show("This will set the match to Full Time and you will be returned to the list of matches." + Environment.NewLine + "Is that ok?", "Finish Match?", MessageBoxButton.OKCancel);

                if (n == MessageBoxResult.OK)
                {
                    //string user_idString = (string)settings["Username"];
                    //string user_id;
                    string temp = "FT";
                    timeBlock.Text = Minute.ToString();
                    Score = goalsBox1.Text.ToString() + "-" + pointsBox1.Text.ToString() + " - " + goalsBox2.Text.ToString() + "-" + pointsBox2.Text.ToString();
                    GAALiveServiceClient client = new GAALiveServiceClient();

                    // Code to finish teh match and move it from Live Scores to Results screen
                    client.FinishMatchCompleted +=
                        new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(client_FinishMatchCompleted);
                    client.FinishMatchAsync(dateTime, Location, "N", Score, HomeTeam, AwayTeam, Competition, temp, id, user_id);

                    NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                }
            }

            else
            {
                MessageBox.Show("The second half has not thrown in yet!");
            }

        }

        // Launch camera section of the app
        private void CameraButton_Click(object sender, RoutedEventArgs e)
        {
            if (matchOver)
            {
                MessageBoxResult n = MessageBox.Show("This match has finished, Pease begin a new one if you wish to report on a new match.", "Match finished!", MessageBoxButton.OK);

                if (n == MessageBoxResult.OK)
                {
                    NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                    //NavigationService.GoBack();
                }
            }
            else
            {
                // Making sure here that the match has started
                // down the line this could be changed to allow pre-match pictures to be taken
                if (buttonClicked)
                {
                    string id1;
                    //NavigationService.Navigate(new Uri("/Views/CameraCapture.xaml?ID=" + id, UriKind.Relative));
                    Uri nav = new Uri("/Views/MatchUpdatePage.xaml?HomeTeam=" + HomeTeam + "&AwayTeam=" + AwayTeam + "&Location=" + Location + "&Competition=" + Competition + "&Time=" + Time, UriKind.Relative);
                    NavigationService.Navigate(new Uri("/Views/CameraCapture.xaml?id1=" + id.ToString(), UriKind.Relative));
                }
                else
                {
                    MessageBox.Show("Match has not yet started. Click 'Start Match' to begin.");
                }
            }
            
        }
    }
}